import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Modal,
  Input,
  Table,
  Menu,
  Dropdown,
  Select,
  Button,
  Divider,
  Tooltip,
} from 'antd';

import { DownOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { pathname } = window.location;
const { Item } = Form;

interface SendAPackageListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  INITINFO: any;
  screen: string;
}

interface SendAPackageListState {
  searchValues: any;
  visible: boolean;
  record: any;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(({
  SendAPackageList: { dataInfo },
  common: { INITINFO },
  global: { screen },
  loading,
}: any) => ({
  dataInfo,
  INITINFO,
  screen,
  loading: loading.effects['SendAPackageList/fetch'],
}))
class SendAPackageListElem extends Component<SendAPackageListProps, SendAPackageListState> {
  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 150,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            style={{ maxWidth: '90%' }}
            onClick={() => this.handleShowPackage(record.id, record.name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '地区',
      dataIndex: 'fromProvinceName',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      width: 80,
      render: (text: number) => (text === 1 ? '是' : '否'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 100,
    },
    {
      title: '操作',
      width: 140,
      render: (text: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleSwitchStatus(record)}
          >
            默认
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleShowPackage(record.id, record.name)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={this.menu(record)}>
            <span className="operLink">
              更多<DownOutlined />
            </span>
          </Dropdown>
        </div>
      ),
    },
  ];

  state: SendAPackageListState= {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    visible: false,
    rowId: 0,
    record: {
      id: '',
      isDefault: 1,
    },
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;

    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo } = this.props;
    if (dataInfo?.list?.length) return;

    this.fetchDataValues();
    this.fetchAction('common/fetchAreaList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  }

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  }

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  }

  menu = (record: any) => (
    <Menu>
      <Menu.Item
        className="operLink"
        onClick={() => this.handleConfCompany(record.id, record.name)}
      >配置快递公司
      </Menu.Item>
    </Menu>
  )

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体寄件套餐配置',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const query = {
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体寄件套餐配置',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体寄件套餐配置',
      url: pathname,
      isTopMenu: true,
    });
  }

  handleSwitchStatus = (record: any) => {
    const { id } = record;
    this.setState({
      visible: true,
      record: { id, isDefault: 1 },
    });
  }

  handleConfirm = () => {
    const { record: { id, isDefault }, searchValues: search } = this.state;
    const params = { id, isDefault, search };

    this.fetchAction('changeStatus', params);
    this.handleCancel();
  }

  handleCancel = () => this.setState({ visible: false });

  /**
   * 导入资费
   */
  handleImport = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '导入资费',
      url: '/charges/sendAPackage/list/import',
    });
  }

  /**
   * 查看柜体寄件套餐
   */
  handleShowPackage = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/charges/sendAPackage/list/detail?tariffId=${id}&name=${name}`,
    });
  }

  /**
   * 配置快递公司
   */
  handleConfCompany = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `配置${name}`,
      url: `/charges/sendAPackage/list/courier?tariffId=${id}&name=${name}`,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `SendAPackageList/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      pageIndex,
      pageSize,
      visible,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { areaList },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };
    return (
      <>
        <PageHeader />

        <Card
          bordered={false}
          className="searchForm"
        >
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={6} sm={24}>
                <Item label="　资费名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　选择省份" colon={false}>
                  {getFieldDecorator('fromPcode')(
                    <Select allowClear placeholder="请选择">
                      {areaList.map((item: any) => (
                        <Option key={item.id} value={item.code}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="是否为默认" colon={false}>
                  {getFieldDecorator('isDefault')(
                    <Select allowClear placeholder="请选择">
                      <Option value="0">否</Option>
                      <Option value="1">是</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24} className="flexFeView">
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
                <Button
                  className="addButton smallButton marginL16"
                  type="primary"
                  onClick={this.handleReset}
                >重置
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleImport}
            >
              导入资费
            </Button>
            <Button
              className="smallButton"
              type="primary"
              size="small"
            >
              <a href="/thanos/cabTariff/downloadTemplate">下载模板</a>
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="确认提示"
          visible={visible}
          onOk={this.handleConfirm}
          onCancel={this.handleCancel}
        >
          <p style={{ textAlign: 'center' }}>
            您确定要设置为默认吗？
          </p>
        </Modal>

      </>
    );
  }
}

export default Form.create<SendAPackageListProps>()(SendAPackageListElem);
